package com.xujiang.imitationcompanypj.model;

import android.text.TextUtils;
import com.etekcity.vesync.common.Common;
import com.etekcity.vesync.common.util.Callback3;
import com.etekcity.vesync.common.util.L;
import com.etekcity.vesync.common.util.PreferencesUtils;
import com.xujiang.imitationcompanypj.data.Data;
import com.xujiang.imitationcompanypj.data.model.AccessToken;
import org.joda.time.DateTime;
import java.util.Date;
import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

/**
 * Created by xujiang on 2017/4/5.
 */

public class UserLogin {
    private final String TAG = UserLogin.class.getSimpleName();

    private final static String PREFERENCE_LOGIN_FILE_NAME                 = "user_login";
    private final static String PREFERENCE_LOGIN_ID                        = "id";
    private final static String PREFERENCE_LOGIN_ACCESS_TOKEN              = "access_token";
    private final static String PREFERENCE_LOGIN_ACCESS_TOKEN_TIME_EXPIRED = "access_token_time_expired";
    private final static String PREFERENCE_LOGIN_ACCOUNT                   = "user_account";
    private final static String PREFERENCE_LOGIN_PASSWORD                  = "user_password";

    private final static String PREFERENCE_USER_FILE_NAME  = "user_info";
    private final static String PREFERENCE_USER_ID         = "user_id";
    private final static String PREFERENCE_USER_NAME       = "user_name";
    private final static String PREFERENCE_USER_AVATAR_URL = "user_avatar_url";
    private final static String PREFERENCE_USER_SIGNATURE  = "user_signature";

    public final static String PREFERENCE_LOGIN_HISTORY_FILE_NAME = "user_history";
    public final static String PREFERENCE_LOGIN_HISTORY_ACCOUNT   = "user_account";

    private static UserLogin curUser;

    public static synchronized UserLogin get(){
        if(curUser == null){
            synchronized (UserLogin.class){
                if(curUser == null){
                    curUser = new UserLogin();
                }
            }
        }
        return curUser;
    }

    private boolean login;//当前是否登录
    private String  userId;//用户id
    private String  name;//用户名
    private String  account;//用户账户
    private String  password;//用户密码 ,md5
    private String  avatar;//用户头像
    private String  signature;//用户签名
    private String  accessToken;
    private long    accessTokenTimeExpired;//token过期时间，秒

    public UserLogin(){

    }

    public void logout(){
        clear();
    }

    private void clear() {
        L.d(TAG,"clear:%s",this);
        setAvatar(null).setUserId(null).setName(null).setAccount(null).setPassword(null)
                .setLogin(false).setSignature(null).setAccessToken(null)
                .setAccessTokenTimeExpired(0);
        PreferencesUtils.from(PREFERENCE_LOGIN_FILE_NAME).clear();
        PreferencesUtils.from(PREFERENCE_USER_FILE_NAME).clear();

    }

    /**
     * 读取登陆用户信息
     *
     * */

    public void readLoginInfo(){
        PreferencesUtils userInfo = PreferencesUtils.from(PREFERENCE_USER_FILE_NAME);
        this.userId = userInfo.getString(UserLogin.PREFERENCE_USER_ID);
        this.name = userInfo.getString(UserLogin.PREFERENCE_USER_NAME);
        this.avatar = userInfo.getString(UserLogin.PREFERENCE_USER_AVATAR_URL);
        this.signature = userInfo.getString(UserLogin.PREFERENCE_USER_SIGNATURE);

        PreferencesUtils loginUser = PreferencesUtils.from(PREFERENCE_LOGIN_FILE_NAME);
        this.userId = loginUser.getString(UserLogin.PREFERENCE_LOGIN_ID);
        this.account = loginUser.getString(UserLogin.PREFERENCE_LOGIN_ACCOUNT);
        this.password = loginUser.getString(UserLogin.PREFERENCE_LOGIN_PASSWORD);
        this.accessTokenTimeExpired = loginUser.getLong(UserLogin.PREFERENCE_LOGIN_ACCESS_TOKEN_TIME_EXPIRED);

        this.login = checkLogin(this.accessTokenTimeExpired);
        if(!login){
            return;
        }
        this.accessToken = loginUser.getString(UserLogin.PREFERENCE_LOGIN_ACCESS_TOKEN);
        L.d(TAG,"readLoginInfo:%s",this);
    }

    public boolean checkLogin(long accessTokenTimeExpired){
        if(accessTokenTimeExpired <= 0 ){
            return false;
        }
        if (Common.isDebug()){
            Date date = new Date();
            date.setTime(accessTokenTimeExpired*1000);
            DateTime dateTime = new DateTime(date);
            L.d(TAG,"check login expired time %s",dateTime.toString("yyyy-MM-dd HH:mm:ss"));
        }
        return  DateTime.now().getMillis() <= accessTokenTimeExpired*1000;
    }

    /**
     * IO线程保存登录与用户信息
     * @param callback
     */
    public void saveInfo(final  Callback3 callback){
        Observable
            .just("")
            .subscribeOn(Schedulers.io())
            .map(new Func1<String, Object>() {
                @Override
                public Object call(String s) {
                    saveLoginInfo();
                    saveUserInfo();
                    return null;
                }
            }).observeOn(AndroidSchedulers.mainThread())
            .subscribe(new Action1<Object>() {
                @Override
                public void call(Object o) {
                    L.d(TAG, "saveIno: %s", UserLogin.this);
                    callback.onSuccess();
                }
        }, new Action1<Throwable>() {
            @Override
            public void call(Throwable throwable) {
                L.Log.w(TAG,throwable);
                callback.onError(throwable);
            }
        });
    }

    public void saveUserInfo(){
        PreferencesUtils.from(UserLogin.PREFERENCE_USER_FILE_NAME)
                .put(UserLogin.PREFERENCE_USER_NAME,name)
                .put(UserLogin.PREFERENCE_USER_AVATAR_URL,avatar)
                .put(UserLogin.PREFERENCE_USER_ID,userId)
                .put(UserLogin.PREFERENCE_USER_SIGNATURE,signature)
                .apply();
        L.d(TAG,"saveUserInfo:%s",this);
    }

    public void saveLoginInfo(){
        PreferencesUtils.from(UserLogin.PREFERENCE_LOGIN_HISTORY_FILE_NAME)
                .put(UserLogin.PREFERENCE_LOGIN_HISTORY_ACCOUNT,account).apply();

        PreferencesUtils.from(UserLogin.PREFERENCE_LOGIN_FILE_NAME)
                .put(UserLogin.PREFERENCE_LOGIN_ID, userId)
                .put(UserLogin.PREFERENCE_LOGIN_ACCOUNT, account)
                .put(UserLogin.PREFERENCE_LOGIN_PASSWORD, password)
                .put(UserLogin.PREFERENCE_LOGIN_ACCESS_TOKEN, accessToken)
                .put(UserLogin.PREFERENCE_LOGIN_ACCESS_TOKEN_TIME_EXPIRED, accessTokenTimeExpired)
                .apply();
        L.d(TAG, "saveLoginInfo : %s", this);
    }

    public UserLogin setUSerInfo(User user){
        this.userId = user.getUserId();
        this.name = user.getUserNickName();
        this.avatar = user.getUserPortrait();
        this.signature = user.getUserSignature();
        return this;
    }

    public UserLogin setToken(AccessToken token){
        this.login = true;
        this.userId = token.getId();
        this.accessToken = token.getTk();
        this.accessTokenTimeExpired = token.getLogin_time_expired();
        this.name = token.getUserNickName();
        if (!TextUtils.isEmpty(token.getUserPortrait())) {
            this.avatar = Data.BASE_SERVER_URL + token.getUserPortrait();
        }
        this.signature = token.getUserSignature();
        return this;
    }

    public synchronized boolean isLogin() {
        return login;
    }

    public synchronized UserLogin setLogin(boolean login) {
        this.login = login;
        return this;
    }

    public String getUserId() {
        return userId;
    }

    public UserLogin setUserId(String userId) {
        this.userId = userId;
        return this;
    }

    public String getName() {
        return name;
    }

    public UserLogin setName(String name) {
        this.name = name;
        return this;
    }

    public String getAccount() {
        return account;
    }

    public UserLogin setAccount(String account) {
        this.account = account;
        return this;
    }

    public String getPassword() {
        return password;
    }

    public UserLogin setPassword(String password) {
        this.password = password;
        return this;
    }

    public String getAvatar() {
        return avatar;
    }

    public UserLogin setAvatar(String avatar) {
        this.avatar = avatar;
        return this;
    }

    public String getSignature() {
        return signature;
    }

    public UserLogin setSignature(String signature) {
        this.signature = signature;
        return this;
    }

    public String getAccessToken() {
        return accessToken;
    }

    public UserLogin setAccessToken(String accessToken) {
        this.accessToken = accessToken;
        return this;
    }

    public long getAccessTokenTimeExpired() {
        return accessTokenTimeExpired;
    }

    public UserLogin setAccessTokenTimeExpired(long accessTokenTimeExpired) {
        this.accessTokenTimeExpired = accessTokenTimeExpired;
        return this;
    }


    @Override
    public String toString() {
        return "UserLogin{" +
                "login=" + login +
                ", userId='" + userId + '\'' +
                ", name='" + name + '\'' +
                ", account='" + account + '\'' +
                ", avatar='" + avatar + '\'' +
                ", signature='" + signature + '\'' +
                ", accessToken='" + accessToken + '\'' +
                ", accessTokenTimeExpired=" + accessTokenTimeExpired +
                '}';
    }
}
